# -*- coding: utf-8 -*-
import time
from typing import List

from selenium.webdriver.common.by import By

from zhi_dao import driver
from zhi_dao import driver_action
from zhi_dao.entity.zhidao_course import ZhiDaoCourse
from zhi_dao.reader.zhidao_section_reader import ZhiDaoSectionReader
from threading import Thread


class ZhiDaoCourseSelector:

    courses: List[ZhiDaoCourse]

    def __init__(self, courses: List[ZhiDaoCourse]):
        self.courses = courses

    def select_course(self, course_num: int):
        driver.save_screenshot("sc.png")
        current_course = self.courses[course_num]
        if current_course.url is not None:
            self.select_course_by_url(current_course)
        else:
            self.select_source_by_click(current_course)
        # pub.sendMessage(event_course_selected)
        # ZhiDaoSectionReader().read_sections()
        self.monitor_dialog()
        Thread(target=ZhiDaoSectionReader().read_sections, args=()).start()
        # ZhiDaoSectionReader().read_sections()
        print("课程选择事件发布成功")

    @staticmethod
    def select_source_by_click(course: ZhiDaoCourse):
        # 选择课程
        driver_action.click(course.get_element()).perform()

    @staticmethod
    def select_course_by_url(course: ZhiDaoCourse):
        driver.get(course.url)

    @staticmethod
    def monitor_dialog():
        time.sleep(2)
        dialog = driver.find_elements(By.CSS_SELECTOR, ".dialog-read")
        if len(dialog) != 0:
            dialog_close_btn = dialog[0].find_elements(By.CSS_SELECTOR, ".iconfont.iconguanbi")[0]
            print("close i")
            print(dialog_close_btn)
            if dialog_close_btn is not None:
                time.sleep(1)
                driver_action.click(dialog_close_btn).perform()
